package cn.whb.hrm.service.impl;

import cn.whb.hrm.config.RabbitMqConfig;
import cn.whb.hrm.constant.CourseConstant;
import cn.whb.hrm.doc.CourseDoc;
import cn.whb.hrm.domain.Course;
import cn.whb.hrm.domain.CourseDetail;
import cn.whb.hrm.domain.CourseMarket;
import cn.whb.hrm.domain.CourseType;
import cn.whb.hrm.dto.CourseDto;
import cn.whb.hrm.feign.CourseDocFeignClient;
import cn.whb.hrm.mapper.CourseDetailMapper;
import cn.whb.hrm.mapper.CourseMapper;
import cn.whb.hrm.mapper.CourseMarketMapper;
import cn.whb.hrm.mapper.CourseTypeMapper;
import cn.whb.hrm.query.CourseDocQuery;
import cn.whb.hrm.service.ICourseService;
import cn.whb.hrm.util.AjaxResult;
import cn.whb.hrm.util.encrypt.ValidUtils;
import cn.whb.hrm.vo.UserInfo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whb
 * @since 2021-12-20
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseDetailMapper detailMapper;
    @Autowired
    private CourseMarketMapper marketMapper;
    @Autowired
    private CourseTypeMapper typeMapper;
    @Autowired
    private CourseDocFeignClient courseDocFeignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult save(@Valid CourseDto dto) {
        /**
         * course与detailMapper、marketMapper一对一的关系
         * 通过共同主键来维护
         * 所以先保存course表，将course表的id交给另外两张表
         */
        //用户登录的时候将用户的一些基本信息放在redis中，因此一些信息可以从Redis中获取
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String name = authentication.getName();
        System.out.println(name);
        Object data = redisTemplate.opsForValue().get("userinfo::" + name);
        UserInfo userInfo = JSON.parseObject(JSON.toJSONString(data), UserInfo.class);
        System.err.println(userInfo);

        //保存course表
        Course course = dto.getCourse();
        course.setTenantId(userInfo.getTid());
        course.setTenantName(userInfo.getCompanyName());
        course.setUserName(userInfo.getEmpName());
        course.setUserId(userInfo.getEmpId());
        courseMapper.insert(course);
        //保存coursedetail表
        CourseDetail detail = dto.getCourseDetail();
        detail.setId(course.getId());
        detailMapper.insert(detail);
        //保存coursemarket表
        CourseMarket market = dto.getCourseMarket();
        market.setId(course.getId());
        marketMapper.insert(market);
        return AjaxResult.me();
    }

    @Override
    public AjaxResult onLineCourse(List<Long> ids) {
        ValidUtils.assertNotNull(ids, "上线的课程不能为空，请重新选择");

        List<Course> courses = courseMapper.selectBatchIds(ids);
        AjaxResult result=null;
        //先保存到es里面
        for(Course course:courses){
            CourseDoc courseDoc = courseToDoc(course);
            CourseType type = typeMapper.selectById(course.getCourseTypeId());
            courseDoc.setCourseTypeName(type.getName());
            //保存到es中
             result= courseDocFeignClient.courseOnline(courseDoc);
            if (result.isSuccess()){//es中存入成功之后，在修改状态
                //修改课程状态
                course.setStatus(CourseConstant.ON_LINE);
                courseMapper.updateById(course);
                //将消息放到队列中
                rabbitTemplate.convertAndSend(RabbitMqConfig.COURSE_ONLINE_NOTICE_EXCHANGE, "message.sms", course.getName());
                rabbitTemplate.convertAndSend(RabbitMqConfig.COURSE_ONLINE_NOTICE_EXCHANGE, "message.email", course.getName());
                rabbitTemplate.convertAndSend(RabbitMqConfig.COURSE_ONLINE_NOTICE_EXCHANGE, "message.system", course.getName());
            }else {
                return result;
            }
        }
        //修改状态
        return result;
    }

    @Override
    public AjaxResult offLineCourse(List<Long> ids) {
        ValidUtils.assertNotNull(ids, "下线的课程不能为空，请重新选择");
        List<Course> courses = courseMapper.selectBatchIds(ids);
        AjaxResult result=null;
        //先删除es里面
        for(Course course:courses){
            result = courseDocFeignClient.courseOffLine(course.getId());
            if (result.isSuccess()){//es中存入成功之后，在修改状态
                //修改课程状态
                course.setStatus(CourseConstant.OFF_LINE);
                courseMapper.updateById(course);
            }else {
                return result;
            }
        }
        //修改状态
        return result;
    }


    @Override
    public AjaxResult queryCourses(CourseDocQuery docQuery) {
        AjaxResult result=courseDocFeignClient.queryCourses(docQuery);
        return result;
    }



    private CourseDoc courseToDoc(Course course) {
        CourseDoc courseDoc = new CourseDoc();
        BeanUtils.copyProperties(course,courseDoc);
        CourseDetail courseDetail = detailMapper.selectById(course.getId());
        BeanUtils.copyProperties(courseDetail,courseDoc);
        CourseMarket courseMarket = marketMapper.selectById(course.getId());
        BeanUtils.copyProperties(courseMarket, courseDoc);
        return courseDoc;
    }
}
